package com.cskaoyan.java.object._3equals._1basic;

/**
 * equals方法重写实现排它性时,有两种选择:
 *      1.使用getClass方法.
 *          这种排它性判断非常严格,只要不是同种类型,就直接排除了
 *
 *      2.使用instanceof语法
 *          引用 instanceof 类名/接口名
 *          用来判断引用所指向的对象,是否是后面类名的对象或者子类对象(如果是抽象类和接口,只能是子类对象)
 *          如果是返回true,否则返回false,null instanceof 任何 都返回false
 *
 *          使用instanceof语法做排它性校验,更加灵活,允许传入子类对象来进行比较
 *
 * 总的来说,排它性还是getClass用的多,equals方法允许传入子类对象用instanceof做排它性校验是比较少见的情况
 *
 * @since 14:51
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class Demo {
    public static void main(String[] args) {
        Teacher t1 = new Teacher(10000, 18);
        Teacher t2 = new Teacher(10000, 18);
        System.out.println(t1.equals(t2));

        TeacherSon ts = new TeacherSon(10000, 18);
        System.out.println(t1.equals(ts));
    }
}

class Teacher {
    double salary;
    int age;

    public Teacher(double salary, int age) {
        this.salary = salary;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        // 1.满足自反性
        if (this == obj) {
            return true;
        }
        // 2.满足排它性
        /*if (obj == null || getClass() != obj.getClass()) {
            return false;
        }*/
        if (!(obj instanceof Teacher)) {
            return false;
        }
        // 3.通过比较属性的取值来满足对称性,传递性,一致性
        Teacher target = (Teacher) obj;
        if (salary != target.salary) {
            return false;
        }
        return age == target.age;
    }
}

class TeacherSon extends Teacher {
    public TeacherSon(double salary, int age) {
        super(salary, age);
    }
}
